package com.example.monitordemo.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import lombok.experimental.UtilityClass;
import okhttp3.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;

import static com.example.monitordemo.config.MonitorConfig.LINUX_INSTANCE;
import static com.example.monitordemo.constant.CommonConstant.API_PREFIX;
import static com.example.monitordemo.constant.CommonConstant.RANGE_QUERY_PREFIX;

@UtilityClass
public class PromQLUtil {
    /**
     * http客户端
     */

    private final OkHttpClient httpClient = (OkHttpClient) SpringContextUtil.getBean("httpClient");

    /**
     * 执行一条promQl语句
     * @param promQL
     * @return
     */
    public JSON executePromQl(String promQL){
        System.out.println(promQL);
        Request request = new Request.Builder().url(promQL).build();
        JSON result;
        try {
            Response response = httpClient.newCall(request).execute();
            assert response.body() != null;
            String data = response.body().string();
            //System.out.println("返回结果=》\n" + data + "\n");
            JSON json = JSONUtil.parse(data);
            result = json;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     *
     * @param date
     * @return
     */
    public String parseDateToTime(Date date){
        long t = date.getTime();
        BigDecimal tt = BigDecimal.valueOf(t);
        //保留三维小数
        BigDecimal time = tt.divide(new BigDecimal(1000), 3, RoundingMode.HALF_UP);
        return time.toString();
    }


    /**
     * 时间范围查询
     * @param start 开始时间
     * @param end 结束时间
     * @param step 步长，值越大横坐标越密集
     * @param instance 实例地址
     * @param query 查询语句
     * @return
     */
    public JSON getRangeJson(Date start,Date end,Integer step, String instance, String query) {
        String s = PromQLUtil.parseDateToTime(start);
        String e = PromQLUtil.parseDateToTime(end);
        String promQL;
        promQL = query;
        if (StrUtil.isNotBlank(instance)){
            promQL = promQL.replace(LINUX_INSTANCE,instance);
        }
        String param = StrUtil.format("&start={}&end={}&step={}", s, e, step);
        String executePromQl = API_PREFIX + RANGE_QUERY_PREFIX + "query="+ promQL + param;
        return PromQLUtil.executePromQl(executePromQl);
    }

}
